# coding=utf-8
from selenium import webdriver
from selenium.webdriver.common.by import By
from PIL import Image  # 用于打开图片和对图片处理
import pytesseract  # 用于图片转文字
from selenium import webdriver  # 用于打开网站
import time  # 代码运行停顿
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
# https://blog.csdn.net/ever_peng/article/details/90547299

class VerificationCode:
    def __init__(self):
        options = webdriver.ChromeOptions()
        options.add_argument('--headless')
        options.add_argument('--start-maximized')
        self.driver = webdriver.Chrome(options=options)
        self.driver.implicitly_wait(10)
        self.find_element = self.driver.find_element_by_css_selector

    def get_pictures(self):
        self.driver.get('https://auth.mingyuanyun.com/')  # 打开登陆页面
        WebDriverWait(self.driver, 20).until(
            EC.presence_of_element_located((By.CSS_SELECTOR, '#valiCode'))
        )
        self.driver.save_screenshot('pictures.png')  # 全屏截图
        img = self.find_element('#valiCode')  # 验证码元素位置
        # time.sleep(1)
        location = img.location
        size = img.size  # 获取验证码的大小参数
        left = location['x']
        top = location['y']
        right = left + size['width']
        bottom = top + size['height']
        im = Image.open('pictures.png')
        im = im.crop((left, top, right, bottom))  # 按照验证码的长宽，切割验证码
        im.save('pictures.png')
        im.show()  # 打开切割后的完整验证码
        handle_image_obj = self.delete_spot(im)
        result = self.image_str(handle_image_obj)
        self.find_element("#Username").clear()
        self.find_element("#Username").send_keys("wup06")
        self.find_element("#Password").send_keys("xxxxxxx")
        self.find_element("#SecurityCode").send_keys(result)
        # self.find_element("[name='button']").click()
        try:
            WebDriverWait(self.driver, 5).until(
                EC.presence_of_element_located((By.CSS_SELECTOR, '.user-notice-icon'))
            )
            print("登录成功！")
            WebDriverWait(self.driver, 5).until(
                EC.presence_of_element_located((By.CSS_SELECTOR, "[href='/console/pipelines']"))
            )
            self.find_element("[href='/console/pipelines']").click()

            time.sleep(1)
        except Exception as e:
            print("登录失败！")
            pass
        execute_str = r"""
jQuery.ajax({
    type: 'HEAD', // 获取头信息，type=HEAD即可
    url : window.location.href,
    complete: function( xhr,data ){
        // 获取相关Http Response header
        var wpoInfo = {
            // 服务器端时间
            "date" : xhr.getResponseHeader('Date'),
            // 如果开启了gzip，会返回这个东西
            "contentEncoding" : xhr.getResponseHeader('Content-Encoding'),
            // keep-alive ？ close？
            "connection" : xhr.getResponseHeader('Connection'),
            // 响应长度
            "contentLength" : xhr.getResponseHeader('content-length'),
            // 服务器类型，apache？lighttpd？
            "server" : xhr.getResponseHeader('Server'),
            "vary" : xhr.getResponseHeader('Vary'),
            "transferEncoding" : xhr.getResponseHeader('Transfer-Encoding'),
            // text/html ? text/xml?
            "contentType" : xhr.getResponseHeader('Content-Type'),
            "cacheControl" : xhr.getResponseHeader('Cache-Control'),
            // 生命周期？
            "exprires" : xhr.getResponseHeader('Exprires'),
            "lastModified" : xhr.getResponseHeader('Last-Modified')
        };
        console.log(xhr.getAllResponseHeaders());
        return xhr.getAllResponseHeaders()
    }
});
"""
        print(self.driver.execute_async_script(execute_str))
        self.driver.save_screenshot('loginResult.png')  # 全屏截图
        self.driver.close()  # 处理完验证码后关闭浏览器

    def processing_image(self,image_obj):
        # image_obj = self.get_pictures()  # 获取验证码
        img = image_obj.convert("L")  # 转灰度
        pixdata = img.load()
        w, h = img.size
        threshold = 180
        # 遍历所有像素，大于阈值的为黑色
        for y in range(h):
            for x in range(w):
                if pixdata[x, y] < threshold:
                    pixdata[x, y] = 0
                else:
                    pixdata[x, y] = 255
        return img

    def delete_spot(self,image_obj):
        images = self.processing_image(image_obj)
        data = images.getdata()
        w, h = images.size
        black_point = 0
        for x in range(1, w - 1):
            for y in range(1, h - 1):
                mid_pixel = data[w * y + x]  # 中央像素点像素值
                if mid_pixel < 50:  # 找出上下左右四个方向像素点像素值
                    top_pixel = data[w * (y - 1) + x]
                    left_pixel = data[w * y + (x - 1)]
                    down_pixel = data[w * (y + 1) + x]
                    right_pixel = data[w * y + (x + 1)]
                    # 判断上下左右的黑色像素点总个数
                    if top_pixel < 10:
                        black_point += 1
                    if left_pixel < 10:
                        black_point += 1
                    if down_pixel < 10:
                        black_point += 1
                    if right_pixel < 10:
                        black_point += 1
                    if black_point < 1:
                        images.putpixel((x, y), 255)
                    black_point = 0
        # images.show()
        return images

    def image_str(self,image_obj):
        # image = self.delete_spot(image_obj)
        # 设置pyteseract路径
        pytesseract.pytesseract.tesseract_cmd = r"C:\Program Files\Tesseract-OCR\tesseract.exe"
        result = pytesseract.image_to_string(image_obj)
        print(result)
        return result


if __name__ == '__main__':
    a = VerificationCode()
    a.get_pictures()
    # a.get_pictures()
    # a.image_str()


# driver = webdriver.Chrome()
# driver.implicitly_wait(10)
# driver.get("https://auth.mingyuanyun.com/")
# driver.find_element(By.ID,"Username").clear()
# driver.find_element(By.ID,"Username").send_keys("wup06")
# driver.find_element(By.ID,"Username").send_keys("Password")
